/**
 * 管理员端 - 学生学习进度查看页面脚本
 */
$(document).ready(function() {
    // 初始化
    initPage();
    
    // 绑定事件
    bindEvents();
});

/**
 * 初始化页面
 */
function initPage() {
    // 获取URL参数中的学生ID
    const urlParams = new URLSearchParams(window.location.search);
    const studentId = urlParams.get('studentId');
    
    if (studentId) {
        // 获取学生学习进度数据
        getStudentLearningProgress(studentId);
    } else {
        showMessage('缺少学生ID参数', 'error');
    }
}

/**
 * 绑定事件
 */
function bindEvents() {
    // 返回按钮
    $('#btn-back').click(function() {
        window.history.back();
    });
}

/**
 * 获取学生学习进度数据
 */
function getStudentLearningProgress(studentId) {
    $.ajax({
        url: `/api/admin/student/learning-progress/${studentId}`,
        type: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function(data) {
            // 显示学生基本信息
            displayStudentInfo(data);
            
            // 渲染学科进度
            renderSubjectProgress(data.subjects);
            
            // 渲染最近练习数据
            renderRecentPractice(data.recentPractice);
            
            // 渲染知识点掌握情况
            renderKnowledgePoints(data.knowledgePoints);
        },
        error: function(xhr) {
            console.error('获取学习进度失败', xhr);
            showMessage('获取学习进度失败: ' + getErrorMessage(xhr), 'error');
        }
    });
}

/**
 * 显示学生基本信息
 */
function displayStudentInfo(data) {
    $('#student-id').text(data.studentId || '-');
    $('#student-name').text(data.studentName || '-');
    $('#student-class').text(data.className || '-');
    $('#student-grade').text(data.grade || '-');
}

/**
 * 渲染学科进度
 */
function renderSubjectProgress(subjects) {
    const progressContainer = $('#subject-progress');
    progressContainer.empty();
    
    if (!subjects || subjects.length === 0) {
        progressContainer.append('<div class="alert alert-info">该学生暂无任何学科的学习记录</div>');
        return;
    }
    
    subjects.forEach(subject => {
        const progressBar = `
            <div class="subject-progress-item">
                <div class="subject-name">${subject.name}</div>
                <div class="progress">
                    <div class="progress-bar" role="progressbar" style="width: ${subject.progress}%" 
                        aria-valuenow="${subject.progress}" aria-valuemin="0" aria-valuemax="100">
                        ${subject.progress}%
                    </div>
                </div>
            </div>
        `;
        progressContainer.append(progressBar);
    });
}

/**
 * 渲染最近练习数据
 */
function renderRecentPractice(recentPractice) {
    if (!recentPractice) return;
    
    $('#total-sessions').text(recentPractice.totalSessions || 0);
    $('#total-exercises').text(recentPractice.totalExercises || 0);
    
    // 计算正确率
    let correctRate = 0;
    if (recentPractice.totalExercises > 0 && recentPractice.correctExercises) {
        correctRate = Math.round((recentPractice.correctExercises / recentPractice.totalExercises) * 100);
    }
    $('#correct-rate').text(correctRate + '%');
    
    // 总学习时长
    const totalMinutes = recentPractice.totalTime || 0;
    $('#total-time').text(totalMinutes + '分钟');
}

/**
 * 渲染知识点掌握情况
 */
function renderKnowledgePoints(knowledgePoints) {
    const kpContainer = $('#knowledge-points');
    kpContainer.empty();
    
    if (!knowledgePoints || knowledgePoints.length === 0) {
        kpContainer.append('<div class="alert alert-info">暂无知识点掌握情况数据</div>');
        return;
    }
    
    knowledgePoints.forEach(kp => {
        const mastery = kp.mastery;
        const masteryPercent = Math.round(mastery * 100);
        
        const item = `
            <div class="knowledge-point-item">
                <div class="kp-info">
                    <span class="kp-subject">${kp.subject}</span>
                    <span class="kp-name">${kp.name}</span>
                </div>
                <div class="progress">
                    <div class="progress-bar ${getMasteryColorClass(mastery)}" role="progressbar" 
                        style="width: ${masteryPercent}%" aria-valuenow="${masteryPercent}" 
                        aria-valuemin="0" aria-valuemax="100">
                        ${masteryPercent}%
                    </div>
                </div>
            </div>
        `;
        kpContainer.append(item);
    });
}

/**
 * 根据掌握程度获取对应的颜色类
 */
function getMasteryColorClass(mastery) {
    if (mastery >= 0.8) return 'bg-success';
    if (mastery >= 0.6) return 'bg-info';
    if (mastery >= 0.4) return 'bg-warning';
    return 'bg-danger';
}

/**
 * 显示消息
 */
function showMessage(message, type = 'success') {
    const alertClass = type === 'error' ? 'alert-danger' : 'alert-success';
    const messageHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    
    $('#message-container').html(messageHtml);
    
    // 5秒后自动消失
    setTimeout(() => {
        $('.alert').alert('close');
    }, 5000);
}

/**
 * 获取错误消息
 */
function getErrorMessage(xhr) {
    if (xhr.responseJSON && xhr.responseJSON.message) {
        return xhr.responseJSON.message;
    }
    return xhr.statusText || '未知错误';
} 